package com.niit.musicserve.controller;

import com.alibaba.fastjson.JSONObject;
import com.niit.musicserve.annotation.RequireRole;
import com.niit.musicserve.entity.Singer;
import com.niit.musicserve.entity.Song;
import com.niit.musicserve.service.SingerService;
import com.niit.musicserve.utils.Const;
import com.niit.musicserve.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/singer")
public class SingerController {
	
	@Autowired
	public SingerService singerService;
	
	/**
	 * 添加歌手
	 * @param singer 歌手信息
	 * @return 操作结果
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@RequireRole({"admin"})
	public Result<String> addSinger(@RequestBody Singer singer) {
		
		try{
			
			if(singer.getSingerName() == null || singer.getSingerName().trim().isEmpty()){
				return Result.error("歌手姓名不能为空");
			}
			
			if(singer.getSingerSex() == null){
				return Result.error("歌手性别不能为空");
			}

			
			singer.setSingerName(singer.getSingerName().trim());
			singer.setSingerSex(singer.getSingerSex());
			singer.setSingerLocation(singer.getSingerLocation().trim());
			singer.setSingerIntro(singer.getSingerIntro().trim());
			singer.setSingerFirstLetter(singer.getSingerFirstLetter().trim());
			singer.setSingerBirth(singer.getSingerBirth());
			
			//调用实现接口的插入方法将数据插入数据集并对操作结果进行判断然后输出
			int result = singerService.insertSinger(singer);
			if (result > 0) {
				
				return Result.success("添加歌手成功",null);
			}
			return Result.error("添加歌手失败");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("系统错误：" + e.getMessage());
		}
		
	}
	
	/**
	 * 删除歌手
	 *
	 * @param request 获取前端请求
	 * @return 操作结果
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	@RequireRole({"admin"})
	public Result<String> deleteSinger(HttpServletRequest request) {
		
		try{
			//获取前端请求中的id
			String id = request.getParameter("id");
			
			if (id == null || id.trim().isEmpty()) {
				return Result.error("歌手ID不能为空");
			}
			
			// 安全地进行trim操作
			id = id.trim();
			
			//调用实现层中的根据id删除歌手的方法
			int result = singerService.deleteSingerById(Integer.parseInt(id));
			//输出结果
			if (result > 0){
				return Result.success("删除成功",null);
			}
			return Result.error("删除失败");
		}
		catch (Exception e) {
			e.printStackTrace();
			return Result.error("系统错误：" + e.getMessage());
		}
	}
	
	/**
	 * 更新歌手信息
	 *
	 * @param singer 歌手信息
	 * @return 操作结果
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@RequireRole({"admin"})
	public Result<String> updateSinger(@RequestBody Singer singer ) {
		
		try{
			
			// 参数校验
			if (singer.getSingerId() == null) {
				return Result.error("歌手ID不能为空");
			}
			
			if (singer.getSingerName() == null || singer.getSingerName().trim().isEmpty()){
				return Result.error("歌手名称不能为空");
			}
			
			if (singer.getSingerSex() == null){
				return Result.error("歌手性别不能为空");
			}
			
			// 安全地进行trim操作
			singer.setSingerId(singer.getSingerId());
			singer.setSingerName(singer.getSingerName().trim());
			singer.setSingerSex(singer.getSingerSex());
			singer.setSingerLocation(singer.getSingerLocation().trim());
			singer.setSingerIntro(singer.getSingerIntro().trim());
			singer.setSingerFirstLetter(singer.getSingerFirstLetter().trim());
			
			//调用对应方法并输出结果
			int result = singerService.updateSingerById(singer);
			if (result>0) {
				
				return Result.success("更新成功",null);
			}
			
			return Result.error("更新失败");
		}
		catch (Exception e) {
			e.printStackTrace();
			return Result.error("系统错误：" + e.getMessage());
		}
	}
	
	/**
	 * 获取所有歌手信息
	 *
	 * @param request 获取前端请求
	 * @return 歌手信息
	 */
	@RequestMapping(value = "/allSinger", method = RequestMethod.GET)
	public Result<List<Singer>> allSinger(HttpServletRequest request) {
		
		return Result.success(singerService.allSinger());
	}
	
	/**
	 * 获取特定条件的歌手信息
	 *
	 * @return 歌手信息
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result<JSONObject> listSingers(
		@RequestParam(defaultValue = "1") Integer pageNum,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(required = false) String singerName,
		@RequestParam(required = false) Integer singerSex,
		@RequestParam(required = false) String singerFirstLetter){
		
		try{
			List<Singer> allSingers;
			
			if(singerSex != null){
				allSingers = singerService.singerBySex(singerSex);
			} else if (singerFirstLetter != null && !singerFirstLetter.isEmpty()) {
				allSingers = singerService.singerByFirstLetter(singerFirstLetter);
			} else if (singerName != null && !singerName.isEmpty()) {
				allSingers = singerService.singerByName("%" + singerName + "%");
			} else {
				allSingers = singerService.allSinger();
			}
			
			int total = allSingers.size();
			int startIndex = (pageNum - 1) * pageSize;
			int endIndex = Math.min(startIndex + pageSize, total);
			
			List<Singer> pageSingers = allSingers.subList(startIndex, endIndex);
			
			JSONObject result = new JSONObject();
			result.put("list", pageSingers);
			result.put("total", total);
			result.put("pageNum", pageNum);
			result.put("pageSize", pageSize);
			result.put("pages", (int) Math.ceil((double) total / pageSize));
			
			return Result.success("查询成功", result);
		}
		catch (Exception e) {
			e.printStackTrace();
			return Result.error("查询失败：" + e.getMessage());
		}
	}
	
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public Result<JSONObject> searchSingers(
		@RequestParam(required = false) String keywords,
		@RequestParam(defaultValue = "1") Integer pageNum,
		@RequestParam(defaultValue = "10") Integer pageSize) {
		
		try {
			List<Singer> singers;
			
			if (keywords != null && !keywords.trim().isEmpty()) {
				// 如果有关键词，进行模糊搜索
				singers = singerService.singerByName(keywords.trim());
			} else {
				// 如果没有关键词，返回所有歌曲
				singers = singerService.allSinger();
			}
			
			// 计算分页数据
			int total = singers.size();
			int startIndex = (pageNum - 1) * pageSize;
			int endIndex = Math.min(startIndex + pageSize, total);
			
			// 获取当前页的歌曲列表
			List<Singer> pageSingers = startIndex < total ? singers.subList(startIndex, endIndex) : List.of();
			
			// 构造返回结果
			JSONObject result = new JSONObject();
			result.put("list", pageSingers);
			result.put("total", total);
			result.put("pageNum", pageNum);
			result.put("pageSize", pageSize);
			result.put("pages", total > 0 ? (int) Math.ceil((double) total / pageSize) : 0);
			
			return Result.success("查询成功", result);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("查询失败: " + e.getMessage());
		}
	}
	
	/**
	 * 获取特定id的歌手信息
	 *
	 * @param request 获取前端请求
	 * @return 歌手信息
	 */
	@RequestMapping(value = "/singerOfId", method = RequestMethod.GET)
	public Result<Singer> singerByPrimary(HttpServletRequest request) {
		
		int singerId = Integer.parseInt(request.getParameter("singerId"));
		
		return Result.success(singerService.singerByPrimaryKey(singerId));
	}
	
	/**
	 * 获取特定姓名的歌手信息
	 *
	 * @param request 获取前端请求
	 * @return 歌手信息
	 */
	@RequestMapping(value = "/singerOfName", method = RequestMethod.GET)
	public Result<List<Singer>> singerByName(HttpServletRequest request) {
		String singerName = request.getParameter("singerName");
		
		return Result.success(singerService.singerByName(singerName));
	}
	
	/**
	 * 获取特定性别的歌手信息
	 *
	 * @param request 获取前端请求
	 * @return 歌手信息
	 */
	@RequestMapping(value = "/singerOfSex", method = RequestMethod.GET)
	public Result<List<Singer>> singerBySex(HttpServletRequest request) {
		String singerSex = request.getParameter("singerSex");
		
		return Result.success(singerService.singerBySex(Integer.parseInt(singerSex)));
	}
	
	/**
	 * 更新歌手图片
	 *
	 * @param avatarFile 歌手图片文件
	 * @param id 歌手id
	 * @return 操作结果
	 */
	@RequestMapping(value = "/singerOfPic", method = RequestMethod.POST)
	@RequireRole({"admin"})
	public Result<String> updateSingerPic(
		@RequestParam("file") MultipartFile avatarFile,
		@RequestParam("id") int id)
	{
		//判断文件是否为空
		if (avatarFile.isEmpty()) {
			return Result.error("文件不能为空");
		}
		
		//设置文件名，为避免重复，这里的文件名格式统一设置为当前时间+原文件名
		String fileName = System.currentTimeMillis() + avatarFile.getOriginalFilename();
		
		//获取文件的存储路径
		String filePath = System.getProperty("user.dir")+ "/res/img/singerPic";
		
		//如若路径不存在，则新建路径
		File file1 = new File(filePath);
		if (! file1.exists()) {
			file1.mkdirs();
		}
		
		//文件实际的路径
		File dest = new File(filePath + System.getProperty("file.separator") + fileName);
		
		//设置文件上传的路径,即存到数据库中的相对路径（注意这里以 / 开头）
		String storeAvatarPath = "/img/singerPic/" + fileName;
		
		try {
			//保存文件
			avatarFile.transferTo(dest);
			
			//调用对应方法，将数据库的图片路径更新
			Singer singer = new Singer();
			singer.setSingerId(id);
			singer.setSingerPic(storeAvatarPath);
			int result = singerService.updateSingerById(singer);
			
			if (result>0) {
				return Result.success("更新成功",null);
			}
			
			return Result.error("更新失败");
			
		}
		catch (IOException e) {
			return Result.error("更新失败" + e.getMessage());
		}
	}
	
	/**
	 * 获取歌手数量
	 *
	 * @param request 获取前端请求
	 * @return 歌手数量
	 */
	@RequestMapping(value = "/numberOfSinger", method = RequestMethod.GET)
	public Result<Integer> numberOfSinger(HttpServletRequest request) {
		
		return Result.success(singerService.numberOfSinger());
	}
	
	/**
	 * 根据性别获取歌手数量
	 *
	 * @param request 获取前端请求
	 * @return 歌手数量
	 */
	@RequestMapping(value = "/numberOfSingerBySex", method = RequestMethod.GET)
	public Result<Integer> numberOfSingerBySex(HttpServletRequest request) {
		String singerSex = request.getParameter("sex");
		
		// 添加参数校验
		if (singerSex == null || singerSex.trim().isEmpty()) {
			return Result.error("参数错误: 性别参数不能为空");
		}
		
		try {
			int sex = Integer.parseInt(singerSex);
			return Result.success(singerService.numberOfSingerBySex(sex));
		} catch (NumberFormatException e) {
			return Result.error("参数错误: 性别参数格式不正确");
		}
	}
	
	/**
	 * 获取特定首字母的歌手信息
	 *
	 * @param request 获取前端请求
	 * @return 歌手信息
	 */
	@RequestMapping(value = "/singerOfFirstLetter", method = RequestMethod.GET)
	public Result<List<Singer>> singerByFirstLetter(HttpServletRequest request) {
		String firstLetter = request.getParameter("firstLetter");
		
		return Result.success(singerService.singerByFirstLetter(firstLetter));
	}
	
}
